package com.icoolkj.microservices.product.service;

import com.icoolkj.microservices.product.dto.ProductRequest;
import com.icoolkj.microservices.product.dto.ProductResponse;
import com.icoolkj.microservices.product.model.Product;
import com.icoolkj.microservices.product.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2024/11/10 17:57
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ProductService {

    private final ProductRepository productRepository;

    public void createProduct(ProductRequest productRequest){
        Product product = Product.builder()
                .name(productRequest.getName())
                .description(productRequest.getDescription())
                .price(productRequest.getPrice())
                .build();
        productRepository.save(product);
        log.info("Product {} is saved", product.getId());
    }

    public List<ProductResponse> getAllProducts() {
        List<Product> products = productRepository.findAll();

        return  products.stream().map(this::mapToProductResopnse).toList();
    }

    private ProductResponse mapToProductResopnse(Product product) {
        return ProductResponse.builder()
                .id(product.getId())
                .name(product.getName())
                .description(product.getDescription())
                .price(product.getPrice())
                .build();
    }
}
